package appapi.utils;

import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

/**
 * @version 1.0
 * @author: lc
 * @date: 2021/6/23 17:24
 */
public class ApiHelper {

    //Post方式获取数据
    public static String postDataByStr(String url, String Str) {

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        HttpPost post = new HttpPost(url);
        String result = "";
        try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
            HttpEntity entity = new StringEntity(Str, "UTF-8");
            post.setEntity(entity);
            post.setHeader("Content-type", "application/json");
            try {
                HttpResponse resp = closeableHttpClient.execute(post);
                InputStream respIs = resp.getEntity().getContent();
                byte[] respBytes = IOUtils.toByteArray(respIs);
                result = new String(respBytes, Charset.forName("UTF-8"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    //get方式获取数据
    public static String getDataByStr(String req_url) {
        StringBuffer buffer = new StringBuffer();
        try {
            URL url = new URL(req_url.replace(" ","%20"));
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();
            httpUrlConn.setDoOutput(false);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);

            httpUrlConn.setRequestMethod("GET");
            httpUrlConn.connect();
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();

        } catch (Exception e) {
            System.out.println(e.getStackTrace());
        }
        return buffer.toString();
    }

    //构建查询字符串
    public  static String GetQueryString(Map<String,String> map, String starTime, String endTime, int currPage, int pageSize)
    {
        StringBuilder query=new  StringBuilder();
        query.append("{\"query\":");
        query.append("{\"bool\":{");
        query.append("\"must\":[");
        for (Map.Entry<String, String> entry : map.entrySet()) {

            if(!isBlank(entry.getValue())){
                //大额消费参数值
                if(entry.getKey().equals("bigAmount")){
                    query.append("{\"range\":{\"trdAmount\":{\"gte\": \""+entry.getValue()+"\", \"lte\": \"9999999999\"}}}," );
                }else{
                    query.append("{\"match\":{\""+entry.getKey()+"\":\""+entry.getValue()+"\"}},");
                }
            }
        }
        query.append("{\"range\":{\"trdTrandate\":{\"gte\": \""+starTime+" 00:00:00"+"\", \"lte\": \""+endTime+" 23:59:59"+"\"}}}" );
        query.append("]}},");
        query.append("\"from\":"+(currPage-1)*pageSize+",");
        query.append("\"size\":"+pageSize+",");
        query.append("\"sort\":[{ \"trdTrandate\":{\"order\":\"DESC\"}}]");
        query.append("}");

        return  query.toString();
    }

    //构建查询字符串不分页
    public  static String GetQueryStringNoFrom(Map<String,String> map,String startTime,String endTime)
    {
        StringBuilder query=new  StringBuilder();
        query.append("{\"query\":");
        query.append("{\"bool\":{");
        query.append("\"must\":[");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if(!isBlank(entry.getValue())){
                //大额消费参数值
                if(entry.getKey().equals("bigAmount")){
                    query.append("{\"range\":{\"trdAmount\":{\"gte\": \""+entry.getValue()+"\", \"lte\": \"9999999999\"}}}," );
                }else{
                    query.append("{\"match\":{\""+entry.getKey()+"\":\""+entry.getValue()+"\"}},");
                }
            }
        }
        query.append("{\"range\":{\"trdTrandate\":{\"gte\": \""+startTime+" 00:00:00"+"\", \"lte\": \""+endTime+" 23:59:59"+"\"}}}" );
        query.append("]}},\"size\":500000,");
        query.append("\"sort\":[{ \"trdTrandate\":{\"order\":\"DESC\"}}]");
        query.append("}");

        return  query.toString();
    }

    //字符串转换成时间
    public static Date StringToDate(String strDate){
        Date date=null;
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = formatter.parse(strDate);
        }catch(Exception ex){ date=null; }
        return  date;
    }

    //时间转字符串
    public static String DateToString(Date strDate){
        SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return  formatter.format(strDate);
    }

    public static String postData(String url, Map<String, Object> paramMap) {

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        HttpPost post = new HttpPost(url);
        String result = "";
        try (CloseableHttpClient closeableHttpClient = httpClientBuilder.build()) {
            // HttpEntity entity = new StringEntity(jsonStrData);
            // 修复 POST json 导致中文乱码
            HttpEntity entity = new StringEntity(paramMap.toString(), "UTF-8");
            post.setEntity(entity);
            post.setHeader("Content-type", "application/json");
            HttpResponse resp = closeableHttpClient.execute(post);
            try {
                InputStream respIs = resp.getEntity().getContent();
                byte[] respBytes = IOUtils.toByteArray(respIs);
                result = new String(respBytes, Charset.forName("UTF-8"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            return result;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }
    public static Boolean isBlank(String str) {
        if (str != null){
            str = str.replaceAll("\r\n|\n\r|\n|\r|\f|\t", "");
        }
        if (str == null){
            return true;
        } else if (str.equals("")){
            return true;
        }
        /*
        else if (str.equals("null"))
            return true;
        else if (str.equals("NULL"))
            return true;
        else if (str.equals("(null)"))
            return true;
        else if (str.equals("(NULL)"))
            return true;
        else if (str.trim().length() == 0)
            return true;
       */
        return false;
    }
}
